﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
	using System.Xml.Linq;
	using Noaa.Noaa;

	public partial class _Default : System.Web.UI.Page
	{
		protected void Page_Init(object sender, EventArgs e)
		{
			this.Go.Click += Go_Clicked;
		}

		protected void Go_Clicked(object sender, EventArgs e)
		{
			ShowWeather();
		}

		protected void ShowWeather()
		{
			ndfdXML client = new ndfdXML();

			//Get lat/lon for zipcode
			var zipCode = ZipCode.Text;
			string data = client.LatLonListZipCode(zipCode);
			XDocument document = XDocument.Parse(data);
			var latitudeLongitude = document.Descendants("latLonList").FirstOrDefault();
			if (latitudeLongitude == null || string.IsNullOrEmpty(latitudeLongitude.Value))
			{
				Response.Write("Cannot get latitude / longitude");
				return;
			}

			var location = latitudeLongitude.Value.Split(',');
			decimal latitude;
			if (location.Count() != 2 || !Decimal.TryParse(location[0], out latitude))
			{
				Response.Write("Invalid latitude");
				return;
			}
			decimal longitude;
			if (!Decimal.TryParse(location[1], out longitude))
			{
				Response.Write("Invalid longitude");
				return;
			}
			Response.Write(string.Format("ZipCode: {0}, Latitude {1} Longitude {2}<br/>", zipCode, latitude, longitude));

			//Get max temperature for zip code
			int days = 10;

			weatherParametersType weatherParameters = new weatherParametersType();
			weatherParameters.maxt = true;
			weatherParameters.mint = true;
			data = client.NDFDgenByDay(latitude, longitude, DateTime.Now, days.ToString(), formatType.Item24hourly);
			document = XDocument.Parse(data);
			var parameters = document.Descendants("parameters").FirstOrDefault();
			if (parameters == null)
			{
				Response.Write("Cannot get weather data");
				return;
			}
			var maxTemperatures =
				parameters.Descendants("temperature").FirstOrDefault(
					t => t.Attribute("type") != null && t.Attribute("type").Value == "maximum").Descendants("value").ToList();
			var minTemperatures =
				parameters.Descendants("temperature").FirstOrDefault(
					t => t.Attribute("type") != null && t.Attribute("type").Value == "minimum").Descendants("value").ToList();

			for (int i = 0; i < maxTemperatures.Count; i++)
			{
				var date = DateTime.Now.AddDays(i);

				Response.Write(string.Format("{0:d} min: {1}, max {2}<br/>",
								  date,
								  minTemperatures[i].Value,
								  maxTemperatures[i].Value));
			}
		}
	}
}
